using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.IO;
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
using QualityMetrics = DocumentCreationSystem.Models.QualityMetrics;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 工作流步骤生成器
    /// </summary>
    public class WorkflowStepGenerator
    {
        private readonly ILogger<WorkflowStepGenerator> _logger;
        private readonly IAIService _aiService;

        public WorkflowStepGenerator(ILogger<WorkflowStepGenerator> logger, IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 从AI响应生成步骤
        /// </summary>
        public async Task<List<PlannedWorkflowStep>> GenerateStepsFromAIResponseAsync(string aiResponse, WorkflowStepType defaultType)
        {
            var steps = new List<PlannedWorkflowStep>();

            try
            {
                var lines = aiResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                int priority = 1;

                foreach (var line in lines)
                {
                    if (IsStepLine(line))
                    {
                        var step = ParseStepFromLine(line, defaultType, priority++);
                        if (step != null)
                        {
                            steps.Add(step);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从AI响应生成步骤失败");
            }

            return steps;
        }

        private bool IsStepLine(string line)
        {
            return line.Contains("步骤") || line.Contains("Step") ||
                   line.StartsWith("1.") || line.StartsWith("2.") ||
                   line.StartsWith("-") || line.StartsWith("•");
        }

        private PlannedWorkflowStep? ParseStepFromLine(string line, WorkflowStepType defaultType, int priority)
        {
            try
            {
                var cleanLine = line.Trim().TrimStart('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.', '-', '•', ' ');

                if (string.IsNullOrWhiteSpace(cleanLine))
                    return null;

                var parts = cleanLine.Split('：', ':', '|');
                var name = parts[0].Trim();
                var description = parts.Length > 1 ? parts[1].Trim() : name;

                return new PlannedWorkflowStep
                {
                    Name = name,
                    Description = description,
                    Type = defaultType,
                    Priority = priority,
                    EstimatedDuration = EstimateDuration(description)
                };
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"解析步骤行失败: {line}");
                return null;
            }
        }

        private TimeSpan EstimateDuration(string description)
        {
            // 简单的时间估算逻辑
            if (description.Contains("检查") || description.Contains("验证"))
                return TimeSpan.FromMinutes(2);
            else if (description.Contains("生成") || description.Contains("创建"))
                return TimeSpan.FromMinutes(5);
            else if (description.Contains("分析") || description.Contains("处理"))
                return TimeSpan.FromMinutes(3);
            else
                return TimeSpan.FromMinutes(2);
        }
    }

    /// <summary>
    /// 工作流优化器
    /// </summary>
    public class WorkflowOptimizer
    {
        private readonly ILogger<WorkflowOptimizer> _logger;

        public WorkflowOptimizer(ILogger<WorkflowOptimizer> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 优化工作流
        /// </summary>
        public async Task<WorkflowPlan> OptimizeWorkflowAsync(WorkflowPlan plan)
        {
            try
            {
                _logger.LogInformation($"优化工作流: {plan.Id}");

                // 优化步骤顺序
                OptimizeStepOrder(plan);

                // 优化并行执行
                OptimizeParallelExecution(plan);

                // 优化资源分配
                OptimizeResourceAllocation(plan);

                return plan;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "优化工作流失败");
                return plan;
            }
        }

        private void OptimizeStepOrder(WorkflowPlan plan)
        {
            // 按优先级和依赖关系重新排序
            plan.Steps = plan.Steps.OrderBy(s => s.Priority).ToList();
        }

        private void OptimizeParallelExecution(WorkflowPlan plan)
        {
            // 识别更多可以并行执行的步骤
            var independentSteps = plan.Steps.Where(s =>
                !plan.Dependencies.Any(d => d.ToStepId == s.Id)).ToList();

            if (independentSteps.Count > 1)
            {
                var newParallelGroup = new ParallelExecutionGroup
                {
                    StepIds = independentSteps.Take(2).Select(s => s.Id).ToList(),
                    MaxConcurrency = 2
                };
                plan.ParallelGroups.Add(newParallelGroup);
            }
        }

        private void OptimizeResourceAllocation(WorkflowPlan plan)
        {
            // 优化资源分配逻辑
            foreach (var step in plan.Steps)
            {
                if (step.RequiredResources.Count == 0)
                {
                    step.RequiredResources.Add("CPU");
                    if (step.Type == WorkflowStepType.Generation)
                    {
                        step.RequiredResources.Add("AI_Service");
                    }
                }
            }
        }
    }

    /// <summary>
    /// 工作流执行器
    /// </summary>
    public class WorkflowExecutor
    {
        private readonly ILogger<WorkflowExecutor> _logger;
        private readonly IAIService _aiService;

        public WorkflowExecutor(ILogger<WorkflowExecutor> logger, IAIService aiService)
        {
            _logger = logger;
            _aiService = aiService;
        }

        /// <summary>
        /// 顺序执行工作流
        /// </summary>
        public async Task<WorkflowExecutionResult> ExecuteSequentiallyAsync(WorkflowPlan plan, Models.ExecutionContext context)
        {
            var result = new WorkflowExecutionResult();

            foreach (var step in plan.Steps.OrderBy(s => s.Priority))
            {
                var stepResult = await ExecuteStepAsync(step, context);
                result.StepResults.Add(stepResult);

                if (stepResult.Status == ExecutionStatus.Failed)
                {
                    _logger.LogWarning($"步骤执行失败，停止后续执行: {step.Name}");
                    break;
                }
            }

            return result;
        }

        /// <summary>
        /// 并行执行工作流
        /// </summary>
        public async Task<WorkflowExecutionResult> ExecuteInParallelAsync(WorkflowPlan plan, Models.ExecutionContext context)
        {
            var result = new WorkflowExecutionResult();
            var tasks = new List<Task<StepExecutionResult>>();

            foreach (var step in plan.Steps)
            {
                tasks.Add(ExecuteStepAsync(step, context));
            }

            var stepResults = await Task.WhenAll(tasks);
            result.StepResults.AddRange(stepResults);

            return result;
        }

        /// <summary>
        /// 自适应执行工作流
        /// </summary>
        public async Task<WorkflowExecutionResult> ExecuteAdaptivelyAsync(WorkflowPlan plan, Models.ExecutionContext context)
        {
            // 结合顺序和并行执行的自适应策略
            var result = new WorkflowExecutionResult();

            // 先执行有依赖关系的步骤
            var dependentSteps = plan.Steps.Where(s =>
                plan.Dependencies.Any(d => d.ToStepId == s.Id)).ToList();

            foreach (var step in dependentSteps.OrderBy(s => s.Priority))
            {
                var stepResult = await ExecuteStepAsync(step, context);
                result.StepResults.Add(stepResult);
            }

            // 并行执行独立步骤
            var independentSteps = plan.Steps.Except(dependentSteps).ToList();
            var parallelTasks = independentSteps.Select(step => ExecuteStepAsync(step, context));
            var parallelResults = await Task.WhenAll(parallelTasks);
            result.StepResults.AddRange(parallelResults);

            return result;
        }

        /// <summary>
        /// 执行单个步骤
        /// </summary>
        private async Task<StepExecutionResult> ExecuteStepAsync(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            var result = new StepExecutionResult
            {
                StepId = step.Id,
                StartedAt = DateTime.Now,
                Status = ExecutionStatus.Running
            };

            try
            {
                _logger.LogInformation($"执行步骤: {step.Name}");

                // 根据步骤类型执行不同的逻辑
                switch (step.Type)
                {
                    case WorkflowStepType.AIGeneration:
                        result.Output = await ExecuteAIGenerationStep(step, context);
                        break;
                    case WorkflowStepType.FileOperation:
                        result.Output = await ExecuteFileOperationStep(step, context);
                        break;
                    case WorkflowStepType.DataProcessing:
                        result.Output = await ExecuteDataProcessingStep(step, context);
                        break;
                    case WorkflowStepType.Validation:
                        result.Output = await ExecuteValidationStep(step, context);
                        break;
                    default:
                        result.Output = await ExecuteGenericStep(step, context);
                        break;
                }

                result.Status = ExecutionStatus.Completed;
                result.CompletedAt = DateTime.Now;

                _logger.LogInformation($"步骤执行成功: {step.Name}");
            }
            catch (Exception ex)
            {
                result.Status = ExecutionStatus.Failed;
                result.ErrorMessage = ex.Message;
                result.CompletedAt = DateTime.Now;

                _logger.LogError(ex, $"步骤执行失败: {step.Name}");
            }

            return result;
        }







        /// <summary>






        /// <summary>
        /// 执行AI生成步骤
        /// </summary>
        private async Task<string> ExecuteAIGenerationStep(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            var prompt = GetParameterAsString(step.Parameters, "prompt", step.Description);
            var maxTokens = GetParameterAsInt(step.Parameters, "maxTokens", 2000);
            var temperature = GetParameterAsFloat(step.Parameters, "temperature", 0.7f);

            return await _aiService.GenerateTextAsync(prompt, maxTokens, temperature);
        }

        /// <summary>
        /// 执行文件操作步骤
        /// </summary>
        private async Task<string> ExecuteFileOperationStep(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            var operation = GetParameterAsString(step.Parameters, "operation", "read");
            var filePath = GetParameterAsString(step.Parameters, "filePath", "");

            switch (operation.ToLower())
            {
                case "read":
                    if (File.Exists(filePath))
                    {
                        return await File.ReadAllTextAsync(filePath);
                    }
                    throw new FileNotFoundException($"文件不存在: {filePath}");

                case "write":
                    var content = GetParameterAsString(step.Parameters, "content", "");
                    await File.WriteAllTextAsync(filePath, content);
                    return $"文件已写入: {filePath}";

                case "append":
                    var appendContent = GetParameterAsString(step.Parameters, "content", "");
                    await File.AppendAllTextAsync(filePath, appendContent);
                    return $"内容已追加到文件: {filePath}";

                default:
                    throw new NotSupportedException($"不支持的文件操作: {operation}");
            }
        }

        /// <summary>
        /// 执行数据处理步骤
        /// </summary>
        private async Task<string> ExecuteDataProcessingStep(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            var operation = GetParameterAsString(step.Parameters, "operation", "transform");
            var inputData = GetParameterAsString(step.Parameters, "inputData", "");
            var stringParams = ConvertToStringDictionary(step.Parameters);

            switch (operation.ToLower())
            {
                case "transform":
                    // 数据转换逻辑
                    return await TransformData(inputData, stringParams);

                case "validate":
                    // 数据验证逻辑
                    return await ValidateData(inputData, stringParams);

                case "extract":
                    // 数据提取逻辑
                    return await ExtractData(inputData, stringParams);

                default:
                    throw new NotSupportedException($"不支持的数据处理操作: {operation}");
            }
        }

        /// <summary>
        /// 执行验证步骤
        /// </summary>
        private async Task<string> ExecuteValidationStep(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            var validationType = GetParameterAsString(step.Parameters, "validationType", "content");
            var target = GetParameterAsString(step.Parameters, "target", "");
            var stringParams = ConvertToStringDictionary(step.Parameters);

            switch (validationType.ToLower())
            {
                case "content":
                    return await ValidateContent(target, stringParams);

                case "format":
                    return await ValidateFormat(target, stringParams);

                case "quality":
                    return await ValidateQuality(target, stringParams);

                default:
                    throw new NotSupportedException($"不支持的验证类型: {validationType}");
            }
        }

        /// <summary>
        /// 执行通用步骤
        /// </summary>
        private async Task<string> ExecuteGenericStep(PlannedWorkflowStep step, Models.ExecutionContext context)
        {
            // 通用步骤执行逻辑
            await Task.Delay(100); // 模拟执行时间
            return $"步骤 {step.Name} 执行完成";
        }

        // 辅助方法
        private async Task<string> TransformData(string inputData, Dictionary<string, string> parameters)
        {
            // 简化的数据转换实现
            await Task.Delay(50);
            return $"转换后的数据: {inputData}";
        }

        private async Task<string> ValidateData(string inputData, Dictionary<string, string> parameters)
        {
            // 简化的数据验证实现
            await Task.Delay(50);
            return "数据验证通过";
        }

        private async Task<string> ExtractData(string inputData, Dictionary<string, string> parameters)
        {
            // 简化的数据提取实现
            await Task.Delay(50);
            return $"提取的数据: {inputData.Substring(0, Math.Min(100, inputData.Length))}";
        }

        private async Task<string> ValidateContent(string content, Dictionary<string, string> parameters)
        {
            var criteria = parameters.GetValueOrDefault("criteria", "quality,consistency,completeness");
            var prompt = $"请验证以下内容的{criteria}:\n\n{content}\n\n验证结果:";

            return await _aiService.GenerateTextAsync(prompt, 1000, 0.3f);
        }

        private async Task<string> ValidateFormat(string content, Dictionary<string, string> parameters)
        {
            var expectedFormat = parameters.GetValueOrDefault("expectedFormat", "text");

            // 简化的格式验证
            await Task.Delay(50);
            return $"格式验证: {expectedFormat} - 通过";
        }

        private async Task<string> ValidateQuality(string content, Dictionary<string, string> parameters)
        {
            var qualityThreshold = float.Parse(parameters.GetValueOrDefault("qualityThreshold", "0.8"));
            var prompt = $"请评估以下内容的质量(0-1分):\n\n{content}\n\n质量评分:";

            var result = await _aiService.GenerateTextAsync(prompt, 200, 0.3f);
            return $"质量验证: {result}";
        }

        /// <summary>
        /// 获取参数作为字符串
        /// </summary>
        private string GetParameterAsString(Dictionary<string, object> parameters, string key, string defaultValue)
        {
            if (parameters.TryGetValue(key, out var value))
            {
                return value?.ToString() ?? defaultValue;
            }
            return defaultValue;
        }

        /// <summary>
        /// 获取参数作为整数
        /// </summary>
        private int GetParameterAsInt(Dictionary<string, object> parameters, string key, int defaultValue)
        {
            if (parameters.TryGetValue(key, out var value))
            {
                if (value is int intValue)
                    return intValue;
                if (int.TryParse(value?.ToString(), out var parsedValue))
                    return parsedValue;
            }
            return defaultValue;
        }

        /// <summary>
        /// 获取参数作为浮点数
        /// </summary>
        private float GetParameterAsFloat(Dictionary<string, object> parameters, string key, float defaultValue)
        {
            if (parameters.TryGetValue(key, out var value))
            {
                if (value is float floatValue)
                    return floatValue;
                if (float.TryParse(value?.ToString(), out var parsedValue))
                    return parsedValue;
            }
            return defaultValue;
        }

        /// <summary>
        /// 转换为字符串字典
        /// </summary>
        private Dictionary<string, string> ConvertToStringDictionary(Dictionary<string, object> parameters)
        {
            var result = new Dictionary<string, string>();
            foreach (var kvp in parameters)
            {
                result[kvp.Key] = kvp.Value?.ToString() ?? "";
            }
            return result;
        }
    }



    /// <summary>
    /// 自主执行监控系统
    /// </summary>
    public class ExecutionMonitoringService
    {
        private readonly ILogger<ExecutionMonitoringService> _logger;

        public ExecutionMonitoringService(ILogger<ExecutionMonitoringService> logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 分析执行结果
        /// </summary>
        public async Task<MonitoringResult> AnalyzeExecutionResultAsync(PlanExecutionResult executionResult)
        {
            try
            {
                _logger.LogInformation("分析执行结果");

                var monitoringResult = new MonitoringResult();

                // 计算性能指标
                monitoringResult.PerformanceMetrics = CalculatePerformanceMetrics(executionResult);

                // 计算质量指标
                monitoringResult.QualityMetrics = CalculateQualityMetrics(executionResult);

                // 识别问题
                monitoringResult.Issues = IdentifyIssues(executionResult);

                // 生成建议
                monitoringResult.Recommendations = GenerateRecommendations(executionResult, monitoringResult);

                return monitoringResult;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分析执行结果失败");
                return new MonitoringResult();
            }
        }

        private PerformanceMetrics CalculatePerformanceMetrics(PlanExecutionResult executionResult)
        {
            var metrics = new PerformanceMetrics();

            if (executionResult.CompletedAt.HasValue)
            {
                metrics.ExecutionTime = executionResult.CompletedAt.Value - executionResult.StartedAt;
            }

            if (executionResult.WorkflowExecutionResult != null)
            {
                metrics.TasksCompleted = executionResult.WorkflowExecutionResult.StepResults
                    .Count(r => r.Status == ExecutionStatus.Completed);
                metrics.TasksFailed = executionResult.WorkflowExecutionResult.StepResults
                    .Count(r => r.Status == ExecutionStatus.Failed);

                var totalTasks = executionResult.WorkflowExecutionResult.StepResults.Count;
                metrics.SuccessRate = totalTasks > 0 ? (double)metrics.TasksCompleted / totalTasks : 0;
            }

            return metrics;
        }

        private Models.QualityMetrics CalculateQualityMetrics(PlanExecutionResult executionResult)
        {
            var metrics = new Models.QualityMetrics
            {
                ContentQuality = 0.8, // 默认值，实际应该基于具体分析
                ConsistencyScore = 0.9,
                CompletenessScore = executionResult.Status == ExecutionStatus.Completed ? 1.0 : 0.5
            };

            return metrics;
        }

        private List<string> IdentifyIssues(PlanExecutionResult executionResult)
        {
            var issues = new List<string>();

            if (executionResult.Status == ExecutionStatus.Failed)
            {
                issues.Add($"执行失败: {executionResult.ErrorMessage}");
            }

            if (executionResult.WorkflowExecutionResult != null)
            {
                var failedSteps = executionResult.WorkflowExecutionResult.StepResults
                    .Where(r => r.Status == ExecutionStatus.Failed);

                foreach (var failedStep in failedSteps)
                {
                    issues.Add($"步骤执行失败: {failedStep.StepId} - {failedStep.ErrorMessage}");
                }
            }

            return issues;
        }

        private List<string> GenerateRecommendations(PlanExecutionResult executionResult, MonitoringResult monitoringResult)
        {
            var recommendations = new List<string>();

            if (monitoringResult.PerformanceMetrics.SuccessRate < 0.8)
            {
                recommendations.Add("成功率较低，建议检查步骤设计和依赖关系");
            }

            if (monitoringResult.PerformanceMetrics.ExecutionTime > TimeSpan.FromMinutes(30))
            {
                recommendations.Add("执行时间较长，建议优化并行执行策略");
            }

            if (monitoringResult.Issues.Any())
            {
                recommendations.Add("存在执行问题，建议增加错误处理和重试机制");
            }

            return recommendations;
        }
    }
    /// <summary>
    /// 工作流编排引擎 - 智能生成、优化和执行工作流程
    /// </summary>
    public class WorkflowOrchestrationEngine
    {
        private readonly ILogger<WorkflowOrchestrationEngine> _logger;
        private readonly IAIService _aiService;
        private readonly WorkflowStepGenerator _stepGenerator;
        private readonly WorkflowOptimizer _workflowOptimizer;
        private readonly WorkflowExecutor _workflowExecutor;

        public WorkflowOrchestrationEngine(
            ILogger<WorkflowOrchestrationEngine> logger,
            IAIService aiService,
            WorkflowStepGenerator stepGenerator,
            WorkflowOptimizer workflowOptimizer,
            WorkflowExecutor workflowExecutor)
        {
            _logger = logger;
            _aiService = aiService;
            _stepGenerator = stepGenerator;
            _workflowOptimizer = workflowOptimizer;
            _workflowExecutor = workflowExecutor;
        }

        /// <summary>
        /// 根据用户意图生成工作流规划
        /// </summary>
        public async Task<WorkflowPlan> GenerateWorkflowPlanAsync(EnhancedUserIntent intent)
        {
            try
            {
                _logger.LogInformation("开始生成工作流规划");

                var plan = new WorkflowPlan
                {
                    CreatedAt = DateTime.Now,
                    Strategy = await DetermineWorkflowStrategyAsync(intent)
                };

                // 根据意图类型生成不同的工作流
                var complexIntent = intent.ComplexIntent as ComplexIntent;
                if (complexIntent?.SpecializedIntents.TryGetValue("WorkflowPlanning", out var workflowIntentObj) == true)
                {
                    var workflowIntent = (WorkflowPlanningIntent)workflowIntentObj;
                    
                    switch (workflowIntent.PlanningType)
                    {
                        case WorkflowPlanningType.Automation:
                            await PlanAutomationWorkflowAsync(plan, intent, workflowIntent);
                            break;
                        case WorkflowPlanningType.Batch:
                            await PlanBatchWorkflowAsync(plan, intent, workflowIntent);
                            break;
                        case WorkflowPlanningType.Sequential:
                            await PlanSequentialWorkflowAsync(plan, intent, workflowIntent);
                            break;
                        case WorkflowPlanningType.Parallel:
                            await PlanParallelWorkflowAsync(plan, intent, workflowIntent);
                            break;
                        case WorkflowPlanningType.Monitoring:
                            await PlanMonitoringWorkflowAsync(plan, intent, workflowIntent);
                            break;
                        default:
                            await PlanGeneralWorkflowAsync(plan, intent, workflowIntent);
                            break;
                    }
                }

                // 优化工作流
                plan = await _workflowOptimizer.OptimizeWorkflowAsync(plan);

                _logger.LogInformation($"工作流规划生成完成，包含 {plan.Steps.Count} 个步骤");
                return plan;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成工作流规划失败");
                throw;
            }
        }

        /// <summary>
        /// 执行工作流规划
        /// </summary>
        public async Task<WorkflowExecutionResult> ExecutePlanAsync(WorkflowPlan plan, Models.ExecutionContext context)
        {
            try
            {
                _logger.LogInformation($"开始执行工作流规划: {plan.Id}");

                var result = new WorkflowExecutionResult();

                // 根据执行策略选择执行方式
                switch (plan.Strategy.Mode)
                {
                    case ExecutionMode.Sequential:
                        result = await _workflowExecutor.ExecuteSequentiallyAsync(plan, context);
                        break;
                    case ExecutionMode.Parallel:
                        result = await _workflowExecutor.ExecuteInParallelAsync(plan, context);
                        break;
                    case ExecutionMode.Adaptive:
                        result = await _workflowExecutor.ExecuteAdaptivelyAsync(plan, context);
                        break;
                    default:
                        result = await _workflowExecutor.ExecuteSequentiallyAsync(plan, context);
                        break;
                }

                // 收集执行指标
                result.Metrics["TotalSteps"] = plan.Steps.Count;
                result.Metrics["CompletedSteps"] = result.StepResults.Count(r => r.Status == ExecutionStatus.Completed);
                result.Metrics["FailedSteps"] = result.StepResults.Count(r => r.Status == ExecutionStatus.Failed);

                _logger.LogInformation($"工作流执行完成，成功执行 {result.Metrics["CompletedSteps"]} 个步骤");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行工作流规划失败");
                throw;
            }
        }

        /// <summary>
        /// 确定工作流策略
        /// </summary>
        private async Task<WorkflowExecutionStrategy> DetermineWorkflowStrategyAsync(EnhancedUserIntent intent)
        {
            var strategy = new WorkflowExecutionStrategy
            {
                Name = "智能工作流策略"
            };

            // 根据项目类型和用户需求调整策略
            var complexIntent = intent.ComplexIntent as ComplexIntent;
            if (complexIntent?.Complexity == ComplexityLevel.VeryComplex)
            {
                strategy.Mode = ExecutionMode.Adaptive;
                strategy.MaxConcurrency = 2;
                strategy.Timeout = TimeSpan.FromHours(1);
            }
            else if (complexIntent?.Complexity == ComplexityLevel.Complex)
            {
                strategy.Mode = ExecutionMode.Parallel;
                strategy.MaxConcurrency = 3;
                strategy.Timeout = TimeSpan.FromMinutes(30);
            }
            else
            {
                strategy.Mode = ExecutionMode.Sequential;
                strategy.MaxConcurrency = 1;
                strategy.Timeout = TimeSpan.FromMinutes(15);
            }

            strategy.EnableRetry = true;
            strategy.MaxRetries = 3;

            return strategy;
        }

        /// <summary>
        /// 规划自动化工作流
        /// </summary>
        private async Task PlanAutomationWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            var automationPrompt = BuildAutomationWorkflowPrompt(intent, workflowIntent);
            var aiResponse = await _aiService.GenerateTextAsync(automationPrompt, 3000, 0.8f);
            
            var steps = await _stepGenerator.GenerateStepsFromAIResponseAsync(aiResponse, WorkflowStepType.Generation);
            plan.Steps.AddRange(steps);

            // 添加自动化特有的步骤
            plan.Steps.Insert(0, new PlannedWorkflowStep
            {
                Name = "自动化环境检查",
                Description = "检查自动化执行环境和依赖",
                Type = WorkflowStepType.Validation,
                Priority = 1,
                EstimatedDuration = TimeSpan.FromMinutes(1)
            });

            // 设置并行执行组
            if (plan.Steps.Count > 3)
            {
                var parallelGroup = new ParallelExecutionGroup
                {
                    StepIds = plan.Steps.Skip(2).Take(3).Select(s => s.Id).ToList(),
                    MaxConcurrency = 2
                };
                plan.ParallelGroups.Add(parallelGroup);
            }
        }

        /// <summary>
        /// 规划批量工作流
        /// </summary>
        private async Task PlanBatchWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            var batchPrompt = BuildBatchWorkflowPrompt(intent, workflowIntent);
            var aiResponse = await _aiService.GenerateTextAsync(batchPrompt, 2500, 0.7f);
            
            var steps = await _stepGenerator.GenerateStepsFromAIResponseAsync(aiResponse, WorkflowStepType.Generation);
            plan.Steps.AddRange(steps);

            // 添加批量处理特有的步骤
            plan.Steps.Insert(0, new PlannedWorkflowStep
            {
                Name = "批量任务分析",
                Description = "分析批量处理的任务范围和数量",
                Type = WorkflowStepType.Analysis,
                Priority = 1,
                EstimatedDuration = TimeSpan.FromMinutes(2)
            });

            plan.Steps.Add(new PlannedWorkflowStep
            {
                Name = "批量结果汇总",
                Description = "汇总所有批量处理的结果",
                Type = WorkflowStepType.Integration,
                Priority = plan.Steps.Count + 1,
                EstimatedDuration = TimeSpan.FromMinutes(3)
            });
        }

        /// <summary>
        /// 规划顺序工作流
        /// </summary>
        private async Task PlanSequentialWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            var sequentialPrompt = BuildSequentialWorkflowPrompt(intent, workflowIntent);
            var aiResponse = await _aiService.GenerateTextAsync(sequentialPrompt, 2000, 0.7f);
            
            var steps = await _stepGenerator.GenerateStepsFromAIResponseAsync(aiResponse, WorkflowStepType.Generation);
            plan.Steps.AddRange(steps);

            // 为顺序工作流设置严格的依赖关系
            for (int i = 1; i < plan.Steps.Count; i++)
            {
                plan.Dependencies.Add(new StepDependency
                {
                    FromStepId = plan.Steps[i - 1].Id,
                    ToStepId = plan.Steps[i].Id,
                    Type = DependencyType.Sequential
                });
            }
        }

        /// <summary>
        /// 规划并行工作流
        /// </summary>
        private async Task PlanParallelWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            var parallelPrompt = BuildParallelWorkflowPrompt(intent, workflowIntent);
            var aiResponse = await _aiService.GenerateTextAsync(parallelPrompt, 2500, 0.8f);
            
            var steps = await _stepGenerator.GenerateStepsFromAIResponseAsync(aiResponse, WorkflowStepType.Generation);
            plan.Steps.AddRange(steps);

            // 识别可以并行执行的步骤组
            var parallelGroups = IdentifyParallelGroups(plan.Steps);
            plan.ParallelGroups.AddRange(parallelGroups);
        }

        /// <summary>
        /// 规划监控工作流
        /// </summary>
        private async Task PlanMonitoringWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            // 添加监控特有的步骤
            plan.Steps.AddRange(new[]
            {
                new PlannedWorkflowStep
                {
                    Name = "监控系统初始化",
                    Description = "初始化监控系统和指标收集",
                    Type = WorkflowStepType.Analysis,
                    Priority = 1,
                    EstimatedDuration = TimeSpan.FromMinutes(1)
                },
                new PlannedWorkflowStep
                {
                    Name = "实时状态监控",
                    Description = "持续监控系统状态和性能指标",
                    Type = WorkflowStepType.Analysis,
                    Priority = 2,
                    EstimatedDuration = TimeSpan.FromMinutes(30)
                },
                new PlannedWorkflowStep
                {
                    Name = "异常检测和报警",
                    Description = "检测异常情况并发送报警",
                    Type = WorkflowStepType.Validation,
                    Priority = 3,
                    EstimatedDuration = TimeSpan.FromMinutes(5)
                },
                new PlannedWorkflowStep
                {
                    Name = "监控报告生成",
                    Description = "生成监控报告和分析结果",
                    Type = WorkflowStepType.Output,
                    Priority = 4,
                    EstimatedDuration = TimeSpan.FromMinutes(3)
                }
            });
        }

        /// <summary>
        /// 规划通用工作流
        /// </summary>
        private async Task PlanGeneralWorkflowAsync(WorkflowPlan plan, EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            var generalPrompt = BuildGeneralWorkflowPrompt(intent, workflowIntent);
            var aiResponse = await _aiService.GenerateTextAsync(generalPrompt, 2000, 0.7f);
            
            var steps = await _stepGenerator.GenerateStepsFromAIResponseAsync(aiResponse, WorkflowStepType.Integration);
            plan.Steps.AddRange(steps);
        }

        /// <summary>
        /// 构建自动化工作流提示
        /// </summary>
        private string BuildAutomationWorkflowPrompt(EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            return $@"请设计一个自动化工作流来处理以下需求：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
执行模式：{workflowIntent.ExecutionMode}
目标范围：{workflowIntent.TargetScope}

请提供详细的自动化步骤，包括：
1. 环境准备和检查
2. 自动化任务执行
3. 结果验证和处理
4. 错误处理和恢复

每个步骤请包含：步骤名称、描述、预估时间、所需资源";
        }

        /// <summary>
        /// 构建批量工作流提示
        /// </summary>
        private string BuildBatchWorkflowPrompt(EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            return $@"请设计一个批量处理工作流来处理以下需求：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
所需步骤：{string.Join(", ", workflowIntent.RequiredSteps)}

请提供批量处理的详细步骤，包括：
1. 任务分析和分组
2. 批量处理执行
3. 进度监控
4. 结果汇总

每个步骤请包含：步骤名称、描述、预估时间、输出产物";
        }

        /// <summary>
        /// 构建顺序工作流提示
        /// </summary>
        private string BuildSequentialWorkflowPrompt(EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            return $@"请设计一个顺序执行的工作流来处理以下需求：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}

请提供严格按顺序执行的步骤，确保每个步骤都依赖于前一个步骤的完成。
每个步骤请包含：步骤名称、描述、依赖关系、预估时间";
        }

        /// <summary>
        /// 构建并行工作流提示
        /// </summary>
        private string BuildParallelWorkflowPrompt(EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            return $@"请设计一个支持并行执行的工作流来处理以下需求：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}

请识别可以并行执行的任务组，并提供：
1. 可以并行执行的步骤
2. 必须顺序执行的步骤
3. 步骤间的依赖关系
4. 同步点和汇总步骤

每个步骤请包含：步骤名称、描述、并行组标识、预估时间";
        }

        /// <summary>
        /// 构建通用工作流提示
        /// </summary>
        private string BuildGeneralWorkflowPrompt(EnhancedUserIntent intent, WorkflowPlanningIntent workflowIntent)
        {
            return $@"请根据以下信息设计一个工作流：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
规划类型：{workflowIntent.PlanningType}

请提供合适的工作流步骤来满足用户需求。
每个步骤请包含：步骤名称、描述、类型、预估时间";
        }

        /// <summary>
        /// 识别并行执行组
        /// </summary>
        private List<ParallelExecutionGroup> IdentifyParallelGroups(List<PlannedWorkflowStep> steps)
        {
            var parallelGroups = new List<ParallelExecutionGroup>();

            // 简单的并行组识别逻辑
            // 将相同类型且没有明确依赖关系的步骤分组
            var stepsByType = steps.GroupBy(s => s.Type).Where(g => g.Count() > 1);

            foreach (var group in stepsByType)
            {
                if (group.Count() >= 2)
                {
                    var parallelGroup = new ParallelExecutionGroup
                    {
                        StepIds = group.Take(3).Select(s => s.Id).ToList(), // 最多3个并行
                        MaxConcurrency = Math.Min(group.Count(), 3)
                    };
                    parallelGroups.Add(parallelGroup);
                }
            }

            return parallelGroups;
        }

        /// <summary>
        /// 验证工作流的有效性
        /// </summary>
        public async Task<WorkflowValidationResult> ValidateWorkflowAsync(WorkflowPlan plan)
        {
            try
            {
                _logger.LogInformation($"验证工作流: {plan.Id}");

                var result = new WorkflowValidationResult
                {
                    IsValid = true,
                    ValidationTime = DateTime.Now
                };

                // 检查步骤的完整性
                var completenessIssues = ValidateStepCompleteness(plan.Steps);
                result.Issues.AddRange(completenessIssues);

                // 检查依赖关系的合理性
                var dependencyIssues = ValidateDependencies(plan.Dependencies, plan.Steps);
                result.Issues.AddRange(dependencyIssues);

                // 检查并行组的合理性
                var parallelIssues = ValidateParallelGroups(plan.ParallelGroups, plan.Steps);
                result.Issues.AddRange(parallelIssues);

                // 计算工作流评分
                result.Score = CalculateWorkflowScore(plan);

                result.IsValid = !result.Issues.Any();

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "验证工作流失败");
                return new WorkflowValidationResult { IsValid = false };
            }
        }

        /// <summary>
        /// 验证步骤完整性
        /// </summary>
        private List<string> ValidateStepCompleteness(List<PlannedWorkflowStep> steps)
        {
            var issues = new List<string>();

            if (!steps.Any())
            {
                issues.Add("工作流没有包含任何步骤");
                return issues;
            }

            foreach (var step in steps)
            {
                if (string.IsNullOrWhiteSpace(step.Name))
                {
                    issues.Add($"步骤 {step.Id} 缺少名称");
                }

                if (string.IsNullOrWhiteSpace(step.Description))
                {
                    issues.Add($"步骤 {step.Name} 缺少描述");
                }

                if (step.EstimatedDuration == TimeSpan.Zero)
                {
                    issues.Add($"步骤 {step.Name} 缺少预估时间");
                }
            }

            return issues;
        }

        /// <summary>
        /// 验证依赖关系
        /// </summary>
        private List<string> ValidateDependencies(List<StepDependency> dependencies, List<PlannedWorkflowStep> steps)
        {
            var issues = new List<string>();
            var stepIds = steps.Select(s => s.Id).ToHashSet();

            foreach (var dependency in dependencies)
            {
                if (!stepIds.Contains(dependency.FromStepId))
                {
                    issues.Add($"依赖关系引用了不存在的步骤: {dependency.FromStepId}");
                }

                if (!stepIds.Contains(dependency.ToStepId))
                {
                    issues.Add($"依赖关系引用了不存在的步骤: {dependency.ToStepId}");
                }

                if (dependency.FromStepId == dependency.ToStepId)
                {
                    issues.Add($"步骤不能依赖自己: {dependency.FromStepId}");
                }
            }

            // 检查循环依赖
            if (HasCircularDependencies(dependencies))
            {
                issues.Add("工作流存在循环依赖");
            }

            return issues;
        }

        /// <summary>
        /// 检查循环依赖
        /// </summary>
        private bool HasCircularDependencies(List<StepDependency> dependencies)
        {
            var graph = new Dictionary<string, List<string>>();
            
            foreach (var dep in dependencies)
            {
                if (!graph.ContainsKey(dep.FromStepId))
                    graph[dep.FromStepId] = new List<string>();
                graph[dep.FromStepId].Add(dep.ToStepId);
            }

            var visited = new HashSet<string>();
            var recursionStack = new HashSet<string>();

            foreach (var node in graph.Keys)
            {
                if (HasCycleDFS(node, graph, visited, recursionStack))
                    return true;
            }

            return false;
        }

        /// <summary>
        /// DFS检查循环
        /// </summary>
        private bool HasCycleDFS(string node, Dictionary<string, List<string>> graph, 
            HashSet<string> visited, HashSet<string> recursionStack)
        {
            if (recursionStack.Contains(node))
                return true;

            if (visited.Contains(node))
                return false;

            visited.Add(node);
            recursionStack.Add(node);

            if (graph.ContainsKey(node))
            {
                foreach (var neighbor in graph[node])
                {
                    if (HasCycleDFS(neighbor, graph, visited, recursionStack))
                        return true;
                }
            }

            recursionStack.Remove(node);
            return false;
        }

        /// <summary>
        /// 验证并行组
        /// </summary>
        private List<string> ValidateParallelGroups(List<ParallelExecutionGroup> parallelGroups, List<PlannedWorkflowStep> steps)
        {
            var issues = new List<string>();
            var stepIds = steps.Select(s => s.Id).ToHashSet();

            foreach (var group in parallelGroups)
            {
                foreach (var stepId in group.StepIds)
                {
                    if (!stepIds.Contains(stepId))
                    {
                        issues.Add($"并行组引用了不存在的步骤: {stepId}");
                    }
                }

                if (group.MaxConcurrency <= 0)
                {
                    issues.Add($"并行组 {group.Id} 的最大并发数必须大于0");
                }

                if (group.MaxConcurrency > group.StepIds.Count)
                {
                    issues.Add($"并行组 {group.Id} 的最大并发数不能超过步骤数量");
                }
            }

            return issues;
        }

        /// <summary>
        /// 计算工作流评分
        /// </summary>
        private double CalculateWorkflowScore(WorkflowPlan plan)
        {
            var score = 0.0;

            // 基于步骤数量评分
            var stepScore = Math.Min(plan.Steps.Count / 10.0, 1.0) * 30;

            // 基于依赖关系合理性评分
            var dependencyScore = plan.Dependencies.Any() ? 25 : 15;

            // 基于并行化程度评分
            var parallelScore = plan.ParallelGroups.Any() ? 25 : 15;

            // 基于策略合理性评分
            var strategyScore = 20;

            score = stepScore + dependencyScore + parallelScore + strategyScore;

            return Math.Max(0, Math.Min(100, score));
        }



    }

    /// <summary>
    /// 工作流验证结果
    /// </summary>
    public class WorkflowValidationResult
    {
        public bool IsValid { get; set; }
        public double Score { get; set; }
        public List<string> Issues { get; set; } = new();
        public List<string> Suggestions { get; set; } = new();
        public DateTime ValidationTime { get; set; }
    }
}
